package com.ruoyi.filemanager.command;

import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.filemanager.service.ElfinderStorage;
import com.ruoyi.filemanager.service.VolumeHandler;
import com.ruoyi.filemanager.util.HttpUtil;

public class FileCommand extends AbstractCommand implements ElfinderCommand
{
    public static final String STREAM = "1";

    @Override
    public void execute(ElfinderStorage elfinderStorage, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        String target = request.getParameter("target");
        boolean download = STREAM.equals(request.getParameter("download"));
        VolumeHandler fsi = super.findTarget(elfinderStorage, target);
        String mime = fsi.getMimeType();

        response.setCharacterEncoding(Constants.UTF8);
        response.setContentType(mime);
        String fileName = fsi.getName();
        if (download)
        {
            response.setHeader("Content-Disposition", HttpUtil.safeHttpHeader(
                    "attachments; " + HttpUtil.getAttachementFileName(fileName, request.getHeader("USER-AGENT"))));
            response.setHeader("Content-Transfer-Encoding", "binary");
        }

        OutputStream out = response.getOutputStream();
        response.setContentLength((int) fsi.getSize());

        try (InputStream is = fsi.openInputStream())
        {
            IOUtils.copy(is, out);
            out.flush();
            out.close();
        }
    }
}
